package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.api.scene.query.IQuerySceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.DictionaryDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAccountDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.DictionaryCache;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.ExtOrderInfoCache;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalAttrHelper;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.dataservice.util.IdUtils;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttrValue;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInstAcct;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.base.entity.StaticAttrDO;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <Description> 过户信息-是否过默认账户处理 <br>
 *
 * @author wei.yanhong<br>
 * @version 1.0<br>
 * @since R9.0<br>
 */
@Service
public class TransfDefaultAccctHandler extends AbstractAttrHandler {

    @Autowired
    private IOperateSceneCommonService operateSceneCommonService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Autowired
    private IQuerySceneCommonService querySceneCommonService;

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Override
    public void init(CommonAttrVO commonAttr) {
        // 目前把是否过默认账户配置成98R单选框，没有加载下拉列表值attrValues，需要从缓存中重新获取
        if (KiteListUtils.isEmpty(commonAttr.getAttrValues())) {
            KiteAttr attr = KiteBeanUtils.transform(commonAttr, KiteAttr.class);
            attr.setObjType(LocalKeyConsts.TRANSFER_DISPLAY_OBJECT_TYPE);
            List<AttrValue> attrValueList = AttrValueCache.get(commonAttr.getAttrId());
            attr.setAttrValues(KiteBeanUtils.copyPropsForList(attrValueList, KiteAttrValue.class));
            SpringUtil.getBean(IOperateSceneCommonService.class)
                .setCommonAttr(KiteWebContext.getContext().getCurrentSceneInstId(), attr);
            commonAttr.setAttrValues(KiteBeanUtils.copyPropsForList(attrValueList, StaticAttrDO.class));
        }
        //是否过默认账户初始化为否
        String attrValuesDesc = commonAttr.getAttrValues().stream().filter(staticAttr -> {
            return staticAttr.getAttrValue().equals(commonAttr.getDefaultValue());
        }).map(StaticAttrDO::getAttrValueDesc).findFirst().orElse(null);
        commonAttr.setValue(commonAttr.getDefaultValue());
        commonAttr.setValueDesc(attrValuesDesc);
        setCommonAttr(commonAttr);
    }

    /**
     * 修改是否过默认账户属性
     */
    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {

        //
        if (KiteStringUtils.isNotEmpty(value)) {

            // 过户页面选择是时候，需要从当前实例的账户过户到新客户下
            KitePosDTO kitePosDTO = ExtOrderInfoCache.get(sceneInstId);
            List<KitePosAccountDTO> accounts = kitePosDTO.getAccounts();

            if (KiteListUtils.isNotEmpty(accounts) && "1".equals(value)) {
                dealDefaultAccount(sceneInstId, accounts);
            }
            else {
                KiteAttr acctNameAttr = querySceneCommonService.getCommonAttr(sceneInstId, "acctName")
                    .getResultObject();
                if (Objects.nonNull(acctNameAttr)) {
                    acctNameAttr.setAttrValueTypeId("98F");
                    acctNameAttr.setIsEdit("T");
                    acctNameAttr.setValue("");
                    acctNameAttr.setValueDesc("");
                    operateSceneCommonService.setCommonAttr(sceneInstId, acctNameAttr);
                }
                KiteAttr cbssAcctIdAttr = querySceneCommonService.getCommonAttr(sceneInstId, "cbssAcctId")
                    .getResultObject();
                if (Objects.nonNull(cbssAcctIdAttr)) {
                    cbssAcctIdAttr.setShowType("D");
                    operateSceneCommonService.setCommonAttr(sceneInstId, cbssAcctIdAttr);
                }
                KiteAttr provinceAcctIdAttr = querySceneCommonService.getCommonAttr(sceneInstId, "provinceAcctId")
                    .getResultObject();
                if (Objects.nonNull(provinceAcctIdAttr)) {
                    provinceAcctIdAttr.setShowType("D");
                    operateSceneCommonService.setCommonAttr(sceneInstId, provinceAcctIdAttr);
                }
                KiteAttr payModeAttr = querySceneCommonService.getCommonAttr(sceneInstId, "payMode").getResultObject();
                if (Objects.nonNull(payModeAttr)) {
                    payModeAttr.setValue("");
                    payModeAttr.setValueDesc("");
                    operateSceneCommonService.setCommonAttr(sceneInstId, payModeAttr);
                }
            }
        }
        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }

    private void dealDefaultAccount(String sceneInstId, List<KitePosAccountDTO> accounts) {
        List<KitePosAccountDTO> defaultAcct = accounts.stream().filter(account -> "1".equals(account.getIsDefault()))
            .collect(Collectors.toList());
        KitePosAccountDTO account = KiteListUtils.isEmpty(defaultAcct) ? accounts.get(0) : defaultAcct.get(0);
        // 2 联动设置其他账户属性
        KiteAttr acctNameAttr = querySceneCommonService.getCommonAttr(sceneInstId, "acctName").getResultObject();
        if (Objects.nonNull(acctNameAttr)) {
            acctNameAttr.setAttrValueTypeId("98C");
            acctNameAttr.setIsEdit("T");
            acctNameAttr.setValue(account.getName());
            acctNameAttr.setValueDesc(account.getName());
            operateSceneCommonService.setCommonAttr(sceneInstId, acctNameAttr);
        }
        operateSceneCommonService
            .setCommonAttrValue(sceneInstId, "accountId", account.getAccountId(), account.getAccountId());
        operateSceneCommonService.setCommonAttrValue(sceneInstId, "acctContractCode", account.getAcctContractCode(),
            account.getAcctContractCode());
        operateSceneCommonService.setCommonAttrValue(sceneInstId, "provinceCode", account.getProvinceCode(),
            LocalAttrHelper.getRegionName(account.getProvinceCode()));
        operateSceneCommonService.setCommonAttrValue(sceneInstId, "eparchyCode", account.getEparchyCode(),
            LocalAttrHelper.getRegionName(account.getEparchyCode()));
        operateSceneCommonService
            .setCommonAttrValue(sceneInstId, "openDate", account.getOpenDate(), account.getOpenDate());
        KiteAttr cbssAcctIdAttr = querySceneCommonService.getCommonAttr(sceneInstId, "cbssAcctId").getResultObject();
        if (Objects.nonNull(cbssAcctIdAttr)) {
            cbssAcctIdAttr.setValue(account.getCbssId());
            cbssAcctIdAttr.setValueDesc(account.getCbssId());
            cbssAcctIdAttr.setShowType("E");
            operateSceneCommonService.setCommonAttr(sceneInstId, cbssAcctIdAttr);
        }
        KiteAttr provinceAcctIdAttr = querySceneCommonService.getCommonAttr(sceneInstId, "provinceAcctId")
            .getResultObject();
        if (Objects.nonNull(provinceAcctIdAttr)) {
            provinceAcctIdAttr.setValue(account.getProvinceAcctId());
            provinceAcctIdAttr.setValue(account.getProvinceAcctId());
            provinceAcctIdAttr.setShowType("E");
            operateSceneCommonService.setCommonAttr(sceneInstId, provinceAcctIdAttr);
        }

        // 联动付费关系中的账户信息
        List<DictionaryDTO> dictionaryDTOList = DictionaryCache.get("BUS10007");
        String payModeDesc = "";
        if (KiteListUtils.isNotEmpty(dictionaryDTOList)) {
            String payModeCode = account.getPayMode();
            payModeDesc = dictionaryDTOList.stream()
                .filter(dictionaryDTO -> KiteStringUtils.equals(payModeCode, dictionaryDTO.getCode())).findFirst()
                .map(DictionaryDTO::getValue).orElse("");
            operateSceneCommonService.setCommonAttrValue(sceneInstId, "payMode", account.getPayMode(), payModeDesc);
        }

        // 联动付费关系中的账户信息,生成新的账户实例关系
        List<KiteOfferInstAcct> allAcctRels = new ArrayList<KiteOfferInstAcct>();
        KiteOfferInstAcct offerInstAcctRel = new KiteOfferInstAcct();
        offerInstAcctRel.setInstId(IdUtils.generateInstId(InstType.PROD_INST_ACCT));
        offerInstAcctRel.setAcctId(account.getAccountId());
        offerInstAcctRel.setAcctName(account.getName());
        offerInstAcctRel.setAcctType(account.getOpenDate());
        offerInstAcctRel.setAcctItemId(account.getPayMode());
        offerInstAcctRel.setIsDefault(account.getIsDefault());
        offerInstAcctRel.setAccountCycle(account.getAcctContractCode());
        offerInstAcctRel.setFeeCycle(account.getAcctContractCode());
        offerInstAcctRel.setPayWay("");
        offerInstAcctRel.setPayLimit("");
        offerInstAcctRel.setStartDate("");
        offerInstAcctRel.setEndDate("");
        offerInstAcctRel.setInstType(InstType.OFFER_INST_ACCT);
        offerInstAcctRel.setActionType(ActionType.A);
        allAcctRels.add(offerInstAcctRel);
        operateSceneInstService.putExtParameter(sceneInstId, "offerInstAcctRels", allAcctRels);

        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        account.setCustId(sceneInst.getNewCustId());
        // 3 将过户到的新账户信息塞到缓存 ，后面提交订单转单需要该账户信息
        operateSceneInstService.putExtParameter(sceneInstId, sceneInstId + "_transNewAccountDTO", account);
    }
}
